package com.ccb.jyzx.expand.tiantouonline.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 操作文件和文件夹
 * @projectName: extend
 * @author: jianghaolin
 * @date: 2019/11/21
 * @version: 1.0
 */
public class FileUtils {

    static Logger logger= LoggerFactory.getLogger(FileUtils.class);

    /**
     * 获取tag.txt的名字
     * @return
     */
    public static String getTagTxtName(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date(System.currentTimeMillis());
        String nowDay = df.format(now);
        GregorianCalendar ca = new GregorianCalendar();
        String xx = "";
        if (ca.get(GregorianCalendar.AM_PM) == 0) {
            //上午
            xx = ConstantUtil.BATCH_AM;
        }else{
            //下午
            xx = ConstantUtil.BATCH_PM;
        }
        String tagName = ConstantUtil.TAG_NAME_PAGE + nowDay + "_" + xx + ConstantUtil.TAG_LASTNAME;
        return tagName;
    }

    /**
     * 获取HTML压缩包名字（拷贝复制的HTML目标文件夹名字）
     * @return
     */
    public static String getHtmlTgzName(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date(System.currentTimeMillis());
        String nowDay = df.format(now);
        GregorianCalendar ca = new GregorianCalendar();
        String xx = "";
        if (ca.get(GregorianCalendar.AM_PM) == 0) {
            //上午
            xx = ConstantUtil.BATCH_AM;
        }else{
            //下午
            xx = ConstantUtil.BATCH_PM;
        }
        String tgzName = ConstantUtil.HTML_NAME_PAGE + nowDay + "_" + xx + ConstantUtil.TGZ_LASTNAME;
        return tgzName;
    }

    /**
     * 获取HTML压缩包名字（拷贝复制的HTML目标文件夹名字）
     * @return
     */
    public static String getWordTgzName(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date(System.currentTimeMillis());
        String nowDay = df.format(now);
        String tgzName = ConstantUtil.DOC_NAME_PAGE + nowDay + ConstantUtil.TGZ_LASTNAME;
        return tgzName;
    }

    /**
     * 删除文件
     * @param file
     * @return
     */
    public static boolean deleteFile(File file){
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        } else {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteFile(f);
            }
            return file.delete();
        }
    }
    /**
     * 读取某个文件路径下所有的文件
     * @param path
     * @return
     */
    public static List<File> getFiles(String path){
        File root = new File(path);
        List<File> files = new ArrayList<>();
        if(!root.isDirectory()){
            files.add(root);
        }else{
            File[] subFiles = root.listFiles();
            for(File f : subFiles){
                files.addAll(getFiles(f.getAbsolutePath()));
            }
        }
        return files;
    }

    /**
     * 并指定目录下的文件
     * @param path 目录
     * @param lastName 后缀名
     * @param totalSize 文件大小
     * @return
     */
    public static boolean meshFile(String path, String lastName, long totalSize){
        File location = new File(path);
        File targer = new File(location.toString()+lastName);
        File[] source = location.listFiles();
        String[] sourceFileName = new String[source.length];
        for(int i=0; i<source.length; i++){
            File sourceFile = source[i];
            sourceFileName[i] = sourceFile.getName();
        }
        //给文件名字排序
        Integer[] fileNameArr = JavaUtils.sortStrArr(sourceFileName);
        FileOutputStream output = null;
        try {
            output  = new FileOutputStream(targer);
            for(int i=0; i<fileNameArr.length; i++){
                logger.info("执行合并文件第：" + i + "块");
                String filePath = path + "/" + fileNameArr[i];
                File file = new File(filePath);
                FileInputStream input  = null;
                try {
                    input  = new FileInputStream(file);
                    byte[] b = new byte[1024];
                    int n;
                    while((n=input.read(b))!=-1){
                        output.write(b, 0, n);
                    }
                }catch (IOException e){
                    logger.error("读取合并文件出错，读取文件路径："+path+"错误信息："+ e.getMessage());
                }finally {
                    if(input != null){
                        input.close();
                    }
                    if(output != null){
                        output.close();
                    }
                }
            }
        }catch (IOException e){
            logger.error("合并文件出错，错误信息："+ e.getMessage());
        }finally {
                try {
                    if(output != null){
                        output.close();
                    }
                }catch (IOException e){
                    logger.error("关闭输出流报错，错误信息："+ e.getMessage());
                }


        }

        String fileName = path + lastName;
        File afterFile = new File(fileName);
        logger.info("需要计算文件大小的为：" + fileName);
        long afterSize = afterFile.length();
        logger.info("计算文件的大小：" + afterSize);
        logger.info("数据库当中的文件大小：" + totalSize);
        boolean result = false;
        if(afterSize == totalSize){
            logger.info("ok");
            result = true;
        }
        return result;
    }


    /**
     * 拷贝文件
     * @param source 源文件
     * @param target 目标文件
     */
    public static void copyFile(String source, String target){
        String targetPath = target.substring(0,target.lastIndexOf("/"));
        File file = new File(targetPath);
        if(!file.exists()){
            file.mkdirs();
        }
        int n = 0;
        try {
            FileInputStream fis = new FileInputStream(source);
            FileOutputStream fos = new FileOutputStream(target);
            while ((n = fis.read()) != -1) {
                fos.write(n);
            }
            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建文件
     * @param filePath 文件路径（带文件名）
     * @param contents 文件中的内容(每行文字)
     * @return
     */
    public static boolean createFile(String filePath, List<String> contents){
        boolean result = false;
        try {

            File file = new File(filePath);
            File filePathBase = file.getParentFile();
            if(!filePathBase.exists()){
                filePathBase.mkdirs();
            }
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            if(contents != null && contents.size() > 0){
                for(String content : contents){
                    bw.write(content);
                    bw.newLine();
                }
            }
            bw.flush();
            bw.close();
            result = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

}
